package edu.spangler.dang.FriendViewer;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import edu.spangler.dang.FriendViewer.provider.Friends;

/**
 * Helper class that allows for activities to read data from the
 * content provider and place said information in usable objects for
 * extraction/processing.
 * @author Tuan Dang
 */
public class ProcessContentProvider {

	/**
	 * Static method that processes the current information inside the
	 * content provider.
	 * @param context the calling activity's context
	 * @param usernameStrings allow for a separate ArrayList of usernames to be returned
	 * @return an ArrayList containing multiple extracted objects from the content provider
	 */
	public static ArrayList<Object> process(Context context, boolean usernameStrings) {
		ArrayList<Object> objs = new ArrayList<Object>();
		
		Cursor cursor = context.getContentResolver().query(Friends.ContentUri, null, null, null, null);
		
		// Check to see if the content provider isn't empty
		if(!cursor.moveToFirst()) {
			cursor.close();
			return objs;
		}
		
		int nameCol = cursor.getColumnIndex(Friends.Name);
		int latitudeCol = cursor.getColumnIndex(Friends.Latitude);
		int longitudeCol = cursor.getColumnIndex(Friends.Longitude);
		int count = 0;
		
		// Extract the user operating the applications
		FriendObject theUser = new FriendObject(cursor.getString(nameCol), cursor.getDouble(latitudeCol), cursor.getDouble(longitudeCol));
		objs.add(theUser);
		
		// Check to see if there are friends in the content provider
		if(!cursor.moveToNext()) {
			cursor.close();
			objs.add(count);
			return objs;
		}
		
		ArrayList<FriendObject> friends = new ArrayList<FriendObject>();
		ArrayList<String> friendNames = new ArrayList<String>();
		String username = "";

		// Extract friend information from the content provider
		do {
			count++;
			username = cursor.getString(nameCol);
			friends.add(new FriendObject(username, cursor.getDouble(latitudeCol), cursor.getDouble(longitudeCol)));
			if (usernameStrings)
				friendNames.add(username);
		} while (cursor.moveToNext());

		cursor.close();
		
		objs.add(count);
		objs.add(friends);
		if (usernameStrings)
			objs.add(friendNames);
		return objs;
	}
}
